//
//  ClubCodeLoginView.swift
//  77Club
//
//  Created by Apple on 2024/8/29.
//

import UIKit

class ClubCodeLoginView: UIView, UITextFieldDelegate, RaeNetworkProtocol {

    let phoneTextfield = c_make_ex(UITextField.self)
        .bgColor(.white).corner(25).color(.black).font(14.font_medium)
        .placeholder("请输入手机号码").end()
    let codeTextfield = c_make_ex(UITextField.self)
        .bgColor(.white).corner(25).color(.black).font(14.font_medium)
        .placeholder("请输入验证码").end()
    let passwordTextfield = c_make_ex(UITextField.self)
        .bgColor(.white).corner(25).color(.black).font(14.font_medium)
        .placeholder("请输入6~12位密码").end()
    let inviteTextfield = c_make_ex(UITextField.self)
        .bgColor(.white).corner(25).color(.black).font(14.font_medium)
        .placeholder("邀请码（若没有邀请码可不填）").end()
    private let sendButton = c_make_ex(UIButton.self)
        .bgImage(UIImage.colorToImage(color: "#FF831A".toColor))
        .bgImage(UIImage.colorToImage(color: "#FFAA61".toColor.alpha(0.5)),state: .disabled)
        .color(.white).color(.white.alpha(0.5), state: .disabled)
        .corner(16).font(13.font_medium).text("获取验证码").end()

    private var countdownTimer: Timer?
    private var remainingSeconds: Int = 60
    private var backgroundEnterTime: Date?
    
    var sessionid = "" //收到的验证码
    var panduanStr = "1" // 1 代表已经注册 0 代表没有
    
    var updateViewLayout: ((_ isShow: Bool) -> Void)?
    var updateStateBlock: ((_ enable: Bool) -> Void)?
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        subviews{
            phoneTextfield
            codeTextfield
            passwordTextfield
            inviteTextfield
            sendButton
        }
        
        phoneTextfield.leading(16).trailing(16).height(50).top(0)
        codeTextfield.leading(16).trailing(16).height(50)
        codeTextfield.Top == phoneTextfield.Bottom + 24
        passwordTextfield.leading(16).trailing(16).height(50)
        passwordTextfield.Top == codeTextfield.Bottom + 24
        inviteTextfield.leading(16).trailing(16).height(50)
        inviteTextfield.Top == passwordTextfield.Bottom + 24
        sendButton.width(100).height(32)
        sendButton.CenterY == codeTextfield.CenterY
        sendButton.Trailing == codeTextfield.Trailing - 8
        
        phoneTextfield.style { v in
            v.placehold("#7B7D80".toColor, font: 14.font_medium)
            let leftImageV = UIImageView(frame: CGRect(x: 13, y: 13, width: 24, height: 24))
            leftImageV.image = "Login_phone".toImage
            let leftView = UIView(frame: CGRect(x: 0, y: 0, width: 56, height: 50))
            leftView.addSubview(leftImageV)
            v.leftView = leftView
            v.leftViewMode = .always
            v.delegate = self
        }
        codeTextfield.style { v in
            v.placehold("#7B7D80".toColor, font: 14.font_medium)
            let leftImageV = UIImageView(frame: CGRect(x: 13, y: 13, width: 24, height: 24))
            leftImageV.image = "Login_auth".toImage
            let leftView = UIView(frame: CGRect(x: 0, y: 0, width: 56, height: 50))
            leftView.addSubview(leftImageV)
            v.leftView = leftView
            v.leftViewMode = .always
            v.delegate = self
        }
        passwordTextfield.style { v in
            v.placehold("#7B7D80".toColor, font: 14.font_medium)
            let leftImageV = UIImageView(frame: CGRect(x: 13, y: 13, width: 24, height: 24))
            leftImageV.image = "Login_password".toImage
            let leftView = UIView(frame: CGRect(x: 0, y: 0, width: 56, height: 50))
            leftView.addSubview(leftImageV)
            v.leftView = leftView
            v.leftViewMode = .always
            v.isSecureTextEntry = true
            v.delegate = self
        }
        inviteTextfield.style { v in
            v.placehold("#7B7D80".toColor, font: 14.font_medium)
            let leftImageV = UIImageView(frame: CGRect(x: 13, y: 13, width: 24, height: 24))
            leftImageV.image = "Login_InvitationCode".toImage
            let leftView = UIView(frame: CGRect(x: 0, y: 0, width: 56, height: 50))
            leftView.addSubview(leftImageV)
            v.leftView = leftView
            v.leftViewMode = .always
            v.delegate = self
        }
        
        sendButton.isEnabled = false
        passwordTextfield.isHidden = true
        inviteTextfield.isHidden = true
        
        sendButton.addTarget(self, action: #selector(clickSendButtonButton), for: .touchUpInside)
        
        NotificationCenter.default.addObserver(self, selector: #selector(appDidEnterBackground), name: UIApplication.didEnterBackgroundNotification, object: nil)
        NotificationCenter.default.addObserver(self, selector: #selector(appWillEnterForeground), name: UIApplication.willEnterForegroundNotification, object: nil)
    }
    
    func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
        // 当前文本
        let currentText = textField.text ?? ""
        // 输入后的文本
        guard let stringRange = Range(range, in: currentText) else { return false }
        let updatedText = currentText.replacingCharacters(in: stringRange, with: string)
        var maxLength = 11
        if textField == phoneTextfield {
            if updatedText.count == 11 {
                sendButton.isEnabled = true
            }else{
                sendButton.isEnabled = false
            }
        }
        if textField == passwordTextfield {
            maxLength = 12
        }else if textField == codeTextfield {
            maxLength = 6
        }
        updateLoginButtonState()
        // 检查输入后的文本是否超过最大长度
        return updatedText.count <= maxLength
    }
    
    private func updateLoginButtonState(){
        
        if phoneTextfield.text?.count ?? 0 > 0 && codeTextfield.text?.count ?? 0 > 0 {
            if panduanStr == "0" {
                if passwordTextfield.text?.count ?? 0 > 0 {
                    updateStateBlock?(true)
                }else{
                    updateStateBlock?(false)
                }
            }
            updateStateBlock?(true)
        }else{
            updateStateBlock?(false)
        }
    }
    
    func clearInfo(){
        phoneTextfield.text = ""
        codeTextfield.text = ""
        passwordTextfield.text = ""
        inviteTextfield.text = ""
        sendButton.isEnabled = false
        passwordTextfield.isHidden = true
        inviteTextfield.isHidden = true
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
}

//MARK: action
extension ClubCodeLoginView {

    @objc private func clickSendButtonButton(){
        
        guard let phoneNum = phoneTextfield.text, phoneNum.isValidPhoneNumber else {
            "请输入正确的手机号".toast_error
            return
        }
        Task{
            ToastUtil.show()
            let models = await network.request(.sendCode(phone: phoneNum,type: ""),type: ClubCodeLoginModel.self)
            ToastUtil.dismiss()
            if models.isSuccess, let model = models.model {
                self.sessionid = model.sessionid
                self.panduanStr = model.reg
                var isShow = false
                if model.reg == "1" {
                    passwordTextfield.isHidden = true
                    inviteTextfield.isHidden = true
                }else {
                    isShow = true
                    passwordTextfield.isHidden = false
                    inviteTextfield.isHidden = false
                }
                updateViewLayout?(isShow)
                self.sendButton.isEnabled = false
                self.startCountdown()
            }else{
                models.errorMessage?.toast_error
            }
        }
    }
}

//MARK: 验证码倒计时
extension ClubCodeLoginView {
    
    func startCountdown() {
        countdownTimer?.invalidate() // Invalidate any existing timer
        remainingSeconds = 60
        sendButton.setTitle("\(remainingSeconds)秒后重发", for: .normal)
        countdownTimer = Timer.scheduledTimer(timeInterval: 1.0, target: self, selector: #selector(updateCountdown), userInfo: nil, repeats: true)
    }
    
    @objc func updateCountdown() {
        if remainingSeconds > 0 {
            remainingSeconds -= 1
            sendButton.setTitle("\(remainingSeconds)秒后重发", for: .normal)
        } else {
            countdownTimer?.invalidate()
            self.sendButton.isEnabled = true
            sendButton.setTitle("获取验证码", for: .normal)
        }
    }
    
    @objc func appDidEnterBackground() {
            backgroundEnterTime = Date()
        }

    @objc func appWillEnterForeground() {
        if let backgroundEnterTime = backgroundEnterTime {
            let timeInBackground = Date().timeIntervalSince(backgroundEnterTime)
            remainingSeconds -= Int(timeInBackground)
            if remainingSeconds <= 0 {
                remainingSeconds = 0
                countdownTimer?.invalidate()
                self.sendButton.isEnabled = true
                sendButton.setTitle("获取验证码", for: .normal)
            } else {
                sendButton.setTitle("\(remainingSeconds)秒后重发", for: .normal)
            }
        }
    }
}
